<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增项目' : '编辑项目'"
    width="50%"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      label-width="120px"
      :rules="rules"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
      </el-form-item>
      
      <el-form-item label="项目编号" prop="projectCode">
        <el-input v-model="formData.projectCode" placeholder="请输入项目编号" />
      </el-form-item>
      
      <el-form-item label="投资方" prop="investor">
        <el-input v-model="formData.investor" placeholder="请输入投资方" />
      </el-form-item>
      
      <el-form-item label="联系地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入联系地址" />
      </el-form-item>

      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="项目产业类别" prop="industryCategory">
        <el-select
          v-model="formData.industryCategory"
          placeholder="请选择产业类别"
          style="width: 100%"
        >
          <el-option
            v-for="item in industryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="所属园区" prop="parkName">
        <el-input v-model="formData.parkName" placeholder="请输入所属园区" />
      </el-form-item>
      
      <el-form-item label="项目状态" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="请选择项目状态"
          style="width: 100%"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 项目类型字段 -->
      <el-form-item label="项目类型" prop="projectType">
        <el-select
          v-model="formData.projectType"
          placeholder="请选择项目类型"
          style="width: 100%"
        >
          <el-option label="独立选址" value="independent" />
          <el-option label="租赁厂房" value="rental" />
        </el-select>
      </el-form-item>

      <!-- 项目阶段字段 -->
      <el-form-item label="项目阶段" prop="state">
        <el-select
          v-model="formData.state"
          placeholder="请选择项目阶段"
          style="width: 100%"
        >
          <el-option label="在谈" value="inTalk" />
          <el-option label="土地审批" value="landApproval" />
          <el-option label="建设中" value="construction" />
          <el-option label="已完成" value="completion" />
        </el-select>
      </el-form-item>

      <!-- 项目周期字段 -->
      <el-form-item label="项目周期(月)" prop="projectDuration">
        <el-input-number 
          v-model="formData.projectDuration" 
          :min="1" 
          :max="120"
          placeholder="请输入项目周期(月)"
          style="width: 100%"
        />
      </el-form-item>
      
      <!-- 开始施工日期字段 -->
      <el-form-item label="开始施工日期" prop="constructionStartDate">
        <el-date-picker
          v-model="formData.constructionStartDate"
          type="date"
          placeholder="选择开始施工日期"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 项目简介字段 -->
      <el-form-item label="项目简介" prop="description">
        <el-input 
          v-model="formData.description" 
          type="textarea" 
          :rows="4"
          placeholder="请输入项目简介"
        />
      </el-form-item>

      <!-- 企业简介字段 -->
      <el-form-item label="企业简介" prop="investorDescription">
        <el-input 
          v-model="formData.investorDescription" 
          type="textarea" 
          :rows="4"
          placeholder="请输入企业简介"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ loading ? '提交中...' : '确定' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const formRef = ref(null)
const loading = ref(false)

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

const props = defineProps({
  dialogType: {
    type: String,
    default: 'add'
  },
  currentProject: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const dialogVisible = defineModel()

const industryOptions = ref([
  { value: '智能制造', label: '智能制造' },
  { value: '电子信息', label: '电子信息' },
  { value: '生物医药', label: '生物医药' },
  { value: '新能源', label: '新能源' },
  { value: '新材料', label: '新材料' },
  { value: '装备制造', label: '装备制造' }
])

const statusOptions = ref([
  { value: '在谈', label: '在谈' },
  { value: '已签约', label: '已签约' },
  { value: '建设中', label: '建设中' },
  { value: '竣工验收', label: '竣工验收' },
  { value: '审核中', label: '审核中' }
])

const formData = ref({
  projectName: '',
  projectCode: '',
  investor: '',
  address: '',
  contactPerson: '',
  contactPhone: '',
  industryCategory: '',
  parkName: '',
  status: '在谈',
  state: 'inTalk',
  projectType: 'independent',
  description: '',
  investorDescription: '',
  projectDuration: 12,
  constructionStartDate: ''
})

const rules = ref({
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  projectCode: [
    { required: true, message: '请输入项目编号', trigger: 'blur' }
  ],
  investor: [
    { required: true, message: '请输入投资方', trigger: 'blur' }
  ],
  industryCategory: [
    { required: true, message: '请选择产业类别', trigger: 'change' }
  ],
  projectType: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  state: [
    { required: true, message: '请选择项目阶段', trigger: 'change' }
  ]
})

// 监听当前项目变化
watch(() => props.currentProject, (newVal) => {
  if (newVal && Object.keys(newVal).length > 0) {
    formData.value = { 
      ...formData.value, // 保持默认值
      ...newVal // 覆盖当前项目数据
    }
  }
}, { immediate: true })

// 重置表单
const resetForm = () => {
  formData.value = {
    projectName: '',
    projectCode: '',
    investor: '',
    address: '',
    contactPerson: '',
    contactPhone: '',
    industryCategory: '',
    parkName: '',
    status: '在谈',
    state: 'inTalk',
    projectType: 'independent',
    description: '',
    investorDescription: '',
    projectDuration: 12,
    constructionStartDate: ''
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleClose = () => {
  resetForm()
  dialogVisible.value = false
}

const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    loading.value = true

    let response
    if (props.dialogType === 'add') {
      // 调用新增项目接口
      response = await api.post('/api/projects', formData.value)
      ElMessage.success('项目添加成功')
    } else {
      // 调用更新项目接口
      response = await api.put(`/api/projects/${props.currentProject.id}`, formData.value)
      ElMessage.success('项目更新成功')
    }

    // 关闭对话框
    dialogVisible.value = false
    // 触发刷新事件
    emit('refresh')
    
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response) {
      // 后端返回的错误信息
      const errorMsg = error.response.data.message || error.response.data
      ElMessage.error(`操作失败: ${errorMsg}`)
    } else if (error.name === 'AxiosError') {
      ElMessage.error('网络错误，请检查连接')
    } else {
      // 表单验证失败
      ElMessage.error('请填写完整的项目信息')
    }
  } finally {
    loading.value = false
  }
}
</script>